package main

import (
	"copper-cloud/pkg/util"
	"encoding/json"
	"fmt"
	"github.com/go-resty/resty/v2"
	"github.com/srlemon/gen-id/generator"
	"github.com/tidwall/gjson"
	"net/http"
	"os"
	"strconv"
	"time"
)

var (
	client = resty.New()
	ssoCookie = &http.Cookie{
		Name:       "sso-epctoken",
		Value:      "9ABC6D8042D29D3E2A55D0AC3B11B1E623A81D80299B0AC29315D4441D0D6D3B1682A8889B7A810AA92C334F2046B563",
	}
)

func setCash(khmc, zzzh string) error {

	host := "http://yypt-front-spare.sit.91lyd.com"
	cashData := make(map[string]string)
	cashData["skf"] = "1"
	cashData["khmc"] = khmc
	cashData["zzzh"] = zzzh
	cashData["backUrl"] = ""
	cashData["zzje"] = "10000000.00"
	cashData["zzrq"] = "2020-07-15"
	cashData["jtgs"] = "1"
	cashData["xhfId"] = "100121"
	cashResp, err := client.R().SetCookie(&http.Cookie{
		Name:       "JSESSIONID",
		Value:      "DCF8D86DC9BF7793CF9CD392FFF1C681",
		Path:       "/nbgl2Web/",
		Domain:     "yypt-front-spare.sit.91lyd.com",
	}).SetFormData(cashData).Post(host + "/nbgl2Web/swgl/saveHkzzInfoAction.do")

	util.CheckErr(err)

	if cashResp.IsSuccess() {
		return nil
	}
	return err
}

type CC struct {
	FullName             string `json:"fullName"`
	LocationCode         string `json:"locationCode"`
	BizLocationCode      string `json:"bizLocationCode"`
	Nsrsbh               string `json:"nsrsbh"`
	Shxydm               string `json:"shxydm"`
	InternalUsableStatus string `json:"internalUsableStatus"`
	Source               string `json:"source"`
}

func setCustomer(fullName string) (customerId string) {

	headers := make(map[string]string)
	headers["Content-Type"] = "application/json"
	headers["appId"] = "20010100010000"
	headers["timestamp"] = "1467791956367"
	headers["appKey"] = "48778FFD44ADE08A462BF1EF3085BBD2D02613EF"

	client := resty.New()
	host := "http://10.199.137.182"
	uri := "/test/company/saveOrUpdateAgency"

	c := CC{
		FullName:             fullName,
		LocationCode:         "130982",
		BizLocationCode:      "130000",
		Nsrsbh:               "",
		Shxydm:               "",
		InternalUsableStatus: "Y",
		Source:               "214649602167",
	}

	customerResp, _ := client.R().SetHeaders(headers).
		SetBody(c).Post(host + uri)
	time.Sleep(1 * time.Second)
	return gjson.Get(customerResp.String(), "data").String()
}

// 账户
type Account struct {
	CustomerID      string   `json:"customerId"`
	ServiceType     string   `json:"serviceType"`
	ProductIDList   []string `json:"productIdList"`
	InvoiceProperty string   `json:"invoiceProperty"`
	AccountType     string   `json:"accountType"`
	PlatformType    string   `json:"platformType"`
}

func setAccount(customerId string) (identityId string, accountId int) {

	host := "http://10.199.142.51:8080"
	uri := "/opc/account/createAccount"

	headers := make(map[string]string)
	headers["Content-Type"] = "application/json;charset=UTF-8"

	account := Account{
		CustomerID:      customerId,
		ServiceType:     "01",
		ProductIDList:   []string{"32575", "32574", "32573"},
		InvoiceProperty: "1",
		AccountType:     "1",
		PlatformType:    "1",
	}

	accountResp, err := client.R().EnableTrace().
		SetCookie(ssoCookie).
		SetHeaders(headers).SetBody(account).
		Post(host + uri)
	util.CheckErr(err)

	return gjson.Get(accountResp.String(), "data.identityId").String(), int(gjson.Get(accountResp.String(), "data.accountId").Int())
}

type Remittance struct {
	AccountName string `json:"accountName"`
	AccountNo   string `json:"accountNo"`
	AmountEnd   string `json:"amountEnd"`
	AmountStart string `json:"amountStart"`
	DateEnd     string `json:"dateEnd"`
	DateStart   string `json:"dateStart"`
	PageNo      int64  `json:"pageNo"`
	PageSize    int64  `json:"pageSize"`
}

func queryRemittance(accountName, accountNo string) (remittanceId string) {
	host := "http://yypt-front-spare.sit.91lyd.com"

	headerData := make(map[string]string)
	headerData["Content-Type"] = "application/json;charset=UTF-8"

	remittanceQuery := Remittance{
		AccountName: accountName,
		AccountNo:   accountNo,
		AmountEnd:   "",
		AmountStart: "",
		DateEnd:     "",
		DateStart:   "",
		PageNo:      1,
		PageSize:    20,
	}
	remittanceResp, _ := client.R().SetHeaders(headerData).
		SetCookie(ssoCookie).
		SetBody(remittanceQuery).
		Post(host + "/api/opc/pay/queryRemittance")

	remittanceIdList := gjson.GetBytes(remittanceResp.Body(), "data.list")
	fmt.Println("remittanceIdList: ", remittanceIdList)
	return gjson.Get(remittanceIdList.Array()[0].String(), "remittanceId").String()

}

type CashOrder struct {
	DepositBill  `json:"depositBill"`
	InvoiceInfo  `json:"invoiceInfo"`
	DeliveryInfo `json:"deliveryInfo"`
	PaymentWay        string `json:"paymentWay"`
	RemittancePayList []RemittancePay `json:"remittancePayList"`
}

type DepositBill struct {
	CustomerID     string `json:"customerId"`
	IdentityID     string `json:"identityId"`
	AccountID      int    `json:"accountId"`
	DepositAmount  string `json:"depositAmount"`
	CouponAmount   string `json:"couponAmount"`
	EffectiveStart string `json:"effectiveStart"`
	EffectiveEnd   string `json:"effectiveEnd"`
	OperatorID     string `json:"operatorId"`
	SignerID       string `json:"signerId"`
	Remark         string `json:"remark"`
}

type InvoiceInfo struct {
	InvoiceType      string `json:"invoiceType"`
	InvoiceTitleType string `json:"invoiceTitleType"`
	Title            string `json:"title"`
}

type DeliveryInfo struct {
	ReceiverMobile string `json:"receiverMobile"`
	ReceiverEmail  string `json:"receiverEmail"`
}

type RemittancePay struct {
	RemittanceID string `json:"remittanceId"`
	Amount       int    `json:"amount"`
}



func main() {

	var orderList  []interface{}

	num := 1000
	preName := "perf-ac-"

	var fileName = "data-" + strconv.Itoa(int(time.Now().Unix())) + "-" + strconv.Itoa(num) + ".txt"
	f, _ := os.Create(fileName)

	for i := 1; i <= num; i++ {

		g := new(generator.GeneratorData)
		fullName := preName + strconv.Itoa(i)
		cardID := g.GeneratorBankID()
		fmt.Println("fullName: ", fullName)
		fmt.Println("cardID: ", cardID)

		customerId := setCustomer(fullName)
		fmt.Println("customerId: ", customerId)

		//cashErr := setCash(fullName, cardID)
		//util.CheckErr(cashErr)

		//remittanceId := queryRemittance(fullName, cardID)
		//fmt.Println("remittanceId: ", remittanceId)

		identityIdStr, accountId := setAccount(customerId)
		fmt.Println("accountId: ", accountId)
		identityId, _ := strconv.Atoi(identityIdStr)
		fmt.Println("identityId: ", identityId)

		depositBill := DepositBill{
			CustomerID:     customerId,
			IdentityID:     identityIdStr,
			AccountID:      accountId,
			DepositAmount:  "10000000",
			CouponAmount:   "",
			EffectiveStart: "",
			EffectiveEnd:   "",
			OperatorID:     "b763cad2fe2542018602d41fccc4ee39",
			SignerID:       "b763cad2fe2542018602d41fccc4ee39",
			Remark:         "",
		}

		invoiceInfo := InvoiceInfo{
			InvoiceType:      "4",
			InvoiceTitleType: "2",
			Title:            fullName,
		}

		deliveryInfo := DeliveryInfo{
			ReceiverMobile: g.GeneratorPhone(),
			ReceiverEmail:  g.GeneratorEmail(),
		}

		paymentWay := "1"

		//pay := RemittancePay{
		//	RemittanceID: remittanceId,
		//	Amount:       10000000,
		//}

		var remittancePayList []RemittancePay
		//remittancePayList = append(remittancePayList, pay)

		cashOrder := CashOrder{
			DepositBill:       depositBill,
			InvoiceInfo:       invoiceInfo,
			DeliveryInfo:      deliveryInfo,
			PaymentWay:        paymentWay,
			RemittancePayList: remittancePayList,
		}

		headerData := make(map[string]string)
		headerData["Content-Type"] = "application/json;charset=UTF-8"

		resp, _ := client.R().SetCookie(ssoCookie).
			SetHeaders(headerData).SetBody(cashOrder).
			Post("http://10.199.142.51:8080" + "/opc/deposit/createDepositBill")
		fmt.Println("resp: ", resp)

		order := util.SetOrder(customerId, identityId, accountId, false)
		fmt.Println("order: ", order)


		orderList = append(orderList, order)
	}

	mJson,_ := json.Marshal(orderList)
	mString := string(mJson)

	fmt.Println("orderList: ", mString)

	defer f.Close()
	_, _ = f.WriteString(mString)
}

